package com.adinnc;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.conn.ConnectTimeoutException;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Method;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.PopupWindow.OnDismissListener;

import com.adinnc.Util.AutoTextUtil;
import com.adinnc.Util.CheckConnectivity;
import com.adinnc.Util.Constants;
import com.adinnc.Util.SMSHelper;
import com.adinnc.vo.JourneyDetails;
//import com.tjeannin.apprate.AppRate;
import com.tjeannin.apprate.AppRate;

/**
 * @author adinnc
 * 
 */

public class PnrActivity extends Activity implements View.OnClickListener,
		Runnable, Handler.Callback, TextWatcher {

	public static final String PNRSTATUS_APP_PREFS = "PnrStatusAppPrefs";

	private static final boolean EULA_DEFAULT = false;

	/** Called when the activity is first created. */
	private Button submitButton;
	private AutoCompleteTextView pnr;
	private Dialog dialog;
	private ImageView mActionbarMore;
	private LayoutInflater mInflater;
	private List<String> autoPNRNumbers;
	private Toast toast;
	private ToggleButton toggleButton;

	private final Handler mHandler = new Handler(this);

	static final int HANDLE_JOURNEY_DETAILS = 1;

	static final int HANDLE_ERROR = 3;

	private SharedPreferences _settings;
	private LayoutInflater _inflater;
	private View _eula;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		_settings = getSharedPreferences(PNRSTATUS_APP_PREFS, 0);

		if (!hasAgreedToEula()) {
			_inflater = getLayoutInflater();
			_eula = _inflater.inflate(R.layout.eula_dialog_box, null);

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setCancelable(false)
					.setNegativeButton("Disagree",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									Toast.makeText(
											getApplicationContext(),
											"You have to agree to the EULA to continue using Kampr",
											Toast.LENGTH_LONG);
									finish();
								}
							})
					.setPositiveButton("Yes, I agree",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									SharedPreferences.Editor editor = _settings
											.edit();
									editor.putBoolean("agreed_to_eula", true);
									editor.commit();
								}
							});
			AlertDialog alert = builder.create();
			alert.setView(_eula, 0, 0, 0, 0);
			alert.show();
		}

		setContentView(R.layout.main);
		submitButton = (Button) findViewById(R.id.button1);
		pnr = (AutoCompleteTextView) findViewById(R.id.pnr);
		pnr.addTextChangedListener(this);
		// retrieve the saved PNR Numbers.
		List<String> savedPNRs = AutoTextUtil.readList(getApplicationContext(),
				"savedPnr");

		pnr.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, savedPNRs));

		mActionbarMore = (ImageView) findViewById(R.id.actionbar_more);
		
		createprogressDialog();
		submitButton.setOnClickListener(this);
		mActionbarMore.setOnClickListener(this);
		new AppRate(this).setMinDaysUntilPrompt(0).setMinLaunchesUntilPrompt(4)
				.setShowIfAppHasCrashed(false).init();
		toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
		toggleButton.setOnClickListener(this);
	}
	
	public void createprogressDialog(){
		//progress.setVisibility(View.INVISIBLE);
		dialog = new Dialog(this, android.R.style.Theme_Translucent);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //here we set layout of progress dialog
        dialog.setContentView(R.layout.custom_progress_dialog);
        dialog.setCancelable(true);
	}

	public boolean handleMessage(Message msg) {
		if (isFinishing()) {
			return false;
		}
		switch (msg.what) {
		case HANDLE_JOURNEY_DETAILS:
			JourneyDetails vo = (JourneyDetails) msg.obj;
			handleJourneyDetails(vo);
			// progress.setVisibility(View.GONE);
			return true;
		case HANDLE_ERROR:
			String t = (String) msg.obj;
			handleError(t);
			return true;
		default:
			return false;
		}
	}

	private void handleJourneyDetails(JourneyDetails vo) {
		Context packageContext = this;
		Intent intent = new Intent(packageContext, CheckPNRStatusActivity.class);
		intent.putExtra("com.adinnc.rnp.journeyDetail", vo);
		startActivity(intent);
		resetFirstScreen();
	}

	private void resetFirstScreen() {
		//progress.setVisibility(View.GONE);
		dialog.dismiss();
		pnr.setText("");
	}

	private void handleError(String s) {
		//progress.setVisibility(View.GONE);
		dialog.dismiss();
		showMessage(s);
	}

	protected void checkPnrStatus(String pnrNumber) {
		//progress.setVisibility(View.VISIBLE);
		//check whether toast message is there are not before showing the progress dialog
		if(toast != null)
			toast.cancel();
		dialog.show();
		new Thread(this).start();
	}

	/*
	 * Shows warning message
	 * 
	 * @arg msg: warning message
	 */
	public void showMessage(String msg) {
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.toast_layout,
				(ViewGroup) findViewById(R.id.toast_layout_root));

		TextView text = (TextView) layout.findViewById(R.id.text);
		text.setText(msg);
		Context context = getApplicationContext();
		toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setView(layout);
		toast.show();
	}

	/*
	 * On click of the submit button
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	public void onClick(View v) {
		if (v == submitButton) {
			String pnrN = null;
			if (pnr.getText().toString().length() != 0
					&& pnr.getText().toString().length() == 10) { 

				// auto hide the keyboard if the user enters the 10 charcters.
				IBinder windowToken = pnr.getWindowToken();
				hideKeyboard(windowToken, 0);
				pnrN = pnr.getText().toString();

				// if the user entered the correct value store for auto suggest
				autoPNRNumbers = new ArrayList<String>();
				autoPNRNumbers.add(pnrN);

				AutoTextUtil.writeList(getApplicationContext(), autoPNRNumbers,
						"savedPnr");

				// checking the connectivity before call to server
				if (toggleButton.isChecked() && true == CheckConnectivity.checkNow(getApplicationContext())) {
					// run your normal code path here
					// statusText.setText(checkPnrStatus(pnrN));
					checkPnrStatus(pnrN);
				} else if (!toggleButton.isChecked()){
					//send SMS to get the status of PNR Number
					SMSHelper.sendSMS("PNR "+pnr.getText());
				}else {
					// Send a warning message to the user
					showMessage("No internet connection. Please check.");
				}
			} else {
				showMessage("Please enter a valid PNR Number with 10 digits");
			}
		} else if (v == mActionbarMore) {
			moreClicked();
		} else if (v == toggleButton ){
			if(toggleButton.isChecked()){
				//show internet icon
			} else {
				//show message icon
			}
		}
	}

	private void moreClicked() {
		// TODO Auto-generated method stub
		mActionbarMore.setSelected(true);
		mInflater = getLayoutInflater();
		LinearLayout moreContentView = (LinearLayout) mInflater.inflate(
				R.layout.main_more_content, null);

		moreContentView.measure(View.MeasureSpec.UNSPECIFIED,
				View.MeasureSpec.UNSPECIFIED);
		final PopupWindow popupWindow = new PopupWindow(this);
		popupWindow.setBackgroundDrawable(new ColorDrawable(getResources()
				.getColor(R.color.blue_dark)));
		popupWindow.setContentView(moreContentView);
		popupWindow.showAsDropDown(mActionbarMore);
		popupWindow.setTouchable(true);
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setOnDismissListener(new OnDismissListener() {
			public void onDismiss() {
				mActionbarMore.setSelected(false);
			}
		});

		Button aboutButton = (Button) moreContentView
				.findViewById(R.id.main_more_content_about);
		aboutButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startActivity(new Intent(PnrActivity.this, AboutActivity.class));
				popupWindow.dismiss();
			}
		});

		popupWindow.update(moreContentView.getMeasuredWidth(),
				moreContentView.getMeasuredHeight());

	}

	public void run() {
		try {
			Connection.Response respose = Jsoup
					.connect(Constants.RAIL_URL)
					.data("Content-Type", "application/x-www-form-urlencoded",
							"Content-Type",
							"application/x-www-form-urlencoded", "Connection",
							"Keep-Alive", "Host", "www.indianrail.gov.in",
							"Referer", "http://www.indianrail.gov.in",
							"Accept-Encoding", "", "lccp_pnrno1",
							pnr.getText().toString()).method(Method.POST)
					.execute();
			Document document = respose.parse();
			String status = "";
			String matching_text = "Passenger Current Status Enquiry";

			if (document.hasText()
					&& document.select("td.inside_heading_text").first().text()
							.compareTo(matching_text) != 0) {
				status = document.select("td.inside_heading_text").first()
						.text()
						+ "\n";
				status += document.select("H2").first().text();

				setError(status);
				return;
				// set the view for error message
			} else if (document.hasText()
					&& !document.select(".table_border_both").isEmpty()) {

				// Retrieving all the nodes with id = table_border_both
				Elements links = document
						.getElementsByClass("table_border_both");

				System.out.print(links);

				// Generating the journey details
				JourneyDetails journeyDetails = new JourneyDetails(links);

				setJourneyDetails(journeyDetails);

				return;
			} else {
				setError("Not able to process at this time.");
				return;
			}

		} catch (ConnectTimeoutException e) {
			setError("Server timeout, Please try again");
		} catch (SocketTimeoutException e) {
			setError("Server timeout, Please try again");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			setError("Server busy, Please try after some time");
		} catch (Exception e) {
			setError(e.toString());
		}
		return;
	}

	private void setJourneyDetails(JourneyDetails vo) {
		mHandler.obtainMessage(HANDLE_JOURNEY_DETAILS, vo).sendToTarget();
	}

	private void setError(String t) {
		mHandler.obtainMessage(HANDLE_ERROR, t).sendToTarget();
	}

	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub

	}

	private boolean hasAgreedToEula() {
		return _settings.getBoolean("agreed_to_eula", EULA_DEFAULT);
	}

	private static boolean mSoftKeyboardAvailable;

	static {
		try {
			com.adinnc.Util.SoftKeyboard.checkAvailable();
			mSoftKeyboardAvailable = true;
		} catch (Throwable t) {
			mSoftKeyboardAvailable = false;
		}
	}

	private void hideKeyboard(IBinder windowToken, int flags) {
		if (mSoftKeyboardAvailable) {
			(new com.adinnc.Util.SoftKeyboard(this)).hideSoftInputFromWindow(
					windowToken, flags);
		}
	}

}